import json
import os
import re
from typing import Dict

import jinja2
from openpyxl.reader.excel import load_workbook

from conf.config import BASE_DIR, read_file
from utils.format_article import extract_abstract_and_keywords_and_content


def output_txt(output_full_path, txt):
    """
    输出txt文件
    :param output_full_path: 输出文件的全路径
    :param txt: 文本内容
    :return:
    """

    # 写入html文件
    with open(output_full_path, 'w', encoding='utf-8') as f:
        f.write(txt)

    return txt


def output_json(output_full_path, data, ensure_ascii=False):
    """
    输出到json文件
    :param output_full_path:
    :param data:
    :param ensure_ascii:
    :return:
    """
    with open(output_full_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4, ensure_ascii=ensure_ascii)


def output_html(template_file_name, output_full_path, data):
    """
    输出html文件
    :param template_file_name: 模版文件的文件名
    :param output_full_path: 输出文件的全路径
    :param data: 要更新的数据，例如 data = {'name': 'Alice', 'age': 18}
    :return:
    """
    # 配置jinja2在本地文件系统的搜索路径
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(BASE_DIR, "templates")))
    # 加载模板文件
    template = env.get_template(template_file_name)
    # 使用模板对象渲染html
    rendered_html = template.render(data)
    # 写入html文件
    with open(output_full_path, 'w', encoding='utf-8') as f:
        f.write(rendered_html)

    return rendered_html


def output_all_to_excel_sheet(excel_full_path: str, sheet_name: str, txt_dir_path: str):
    """
    输出所有txt到excel某张表
    :param excel_full_path: excel文件的全路径
    :param sheet_name: 表名
    :param txt_dir_path: 文本文件的文件夹路径
    :return:
    """

    filename_list = os.listdir(txt_dir_path)
    for index, filename in enumerate(filename_list):
        file_path = os.path.join(BASE_DIR, f'output/{filename}')
        print(file_path)

        if not file_path.endswith(".txt"):
            continue

        txt = read_file(file_path)
        abstract, keywords, content = extract_abstract_and_keywords_and_content(txt).values()
        print("摘要：", abstract)
        print("关键词：", keywords)
        print("正文：", content)

        # 打开已存在的 Excel 文件
        workbook = load_workbook(filename=excel_full_path)
        # 获取要写入的工作表
        worksheet = workbook[sheet_name]
        # 写入值到特定单元格
        worksheet[f"C{index + 2}"] = f"{abstract}"
        worksheet[f"D{index + 2}"] = f"{keywords}"
        worksheet[f"E{index + 2}"] = f"{content}"
        # 保存更改
        workbook.save(filename=excel_full_path)


def main():
    # output_all_to_excel_sheet(
    #     excel_full_path=os.path.join(BASE_DIR, f"example.xlsx"),
    #     sheet_name="example",
    #     txt_dir_path=os.path.join(BASE_DIR, "output")
    # )
    pass


if __name__ == '__main__':
    main()
